package net.pzc.filechooser;

import java.awt.Cursor;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;

public class ListRootsAction extends Thread {

	private JComboBox ui = null;
	private DefaultComboBoxModel model = null;
	private String initPath = null;

	private FastFileChooser chooser = null;

	public ListRootsAction(JComboBox ui, String initPath, FastFileChooser chooser) {
		this.ui = ui;
		this.chooser = chooser;
		ui.setEnabled(false);
		ui.getParent().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		this.model = (DefaultComboBoxModel) ui.getModel();
		this.initPath = initPath;
	}

	@Override
	public void run() {

		try {
			startWork();
		} catch (Exception e) {
			e.printStackTrace();
		}

		File[] roots = File.listRoots();

		List<File> newRoots = new ArrayList<File>();
		String desktopPath = PathGetter.getDesktop();
		newRoots.add(new File(desktopPath));
		String documentsPath = PathGetter.getDocuments();
		newRoots.add(new File(documentsPath));
		// String userHomePath = System.getProperty("user.home");
		// newRoots.add(new File(userHomePath));
		for (File file : roots) {
			newRoots.add(file);
		}

		int count = 0;
		for (File file : newRoots) {
			count++;

			FileItem fi = new FileItem();
			fi.setAbsolutePath(file.getAbsolutePath());
			if (count == 1 || count == 2 || count == 2) {
				// Desktop
				fi.setName(file.getName());
			} else {
				fi.setName(file.getPath());
			}

			FastFileChooser.make(file, fi, true);

			try {
				updateUI(fi);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		try {
			finishWork();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startWork() throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				model.removeAllElements();
			}

		});
	}

	private void updateUI(final FileItem fi) throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				model.addElement(fi);
			}

		});
	}

	private void finishWork() throws Exception {
		SwingUtilities.invokeAndWait(new Runnable() {

			public void run() {
				ui.getParent().setCursor(Cursor.getDefaultCursor());
				ui.setEnabled(true);
				if (initPath.equals("")) {
					initPath = ((FileItem) model.getElementAt(0)).getAbsolutePath();
				}
				//chooser.setSelectedAbsolutePath(initPath);
				chooser.openAction(true, initPath);
			}

		});
	}
}
